<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title> 
    <style type="text/css">
*{margin: 0;padding: 0;list-style: none}
#div1{width: 100px;height: 100px;background: black;position: absolute;}

    </style>
</head>
<body>
<div id='div1'></div>
<script type="text/javascript">
	
	div1.onmousedown = function(e){
		var ev = e || event;
		var l = ev.clientX - this.offsetLeft;
		var t = ev.clientY - this.offsetTop;

		document.onmousemove = function(e){
			var ev = e || event;
			var needL = ev.clientX-l;
			var needT = ev.clientY -t;
			var maxL = innerWidth - div1.offsetWidth;
			var maxT = innerHeight - div1.offsetHeight;
			//console.log(needT);
			//console.log(needL)

			needL = needL<0?0:needL;
			needT = needT<0?0:needT;
			needL = needL>maxL?maxL:needL;
			needT = needT>maxT?maxT:needT;
			/*

			if(needL<0)needL=0;
			if(needT<0)needT=0;
			if(needL>innerWidth - div1.offsetWidth){
				needL = innerWidth - div1.offsetWidth
			};
			if(needT>innerHeight - div1.offsetHeight){
				needT = innerHeight - div1.offsetHeight;
			}
			*/
			div1.style.left = needL+'px';
			div1.style.top = needT +'px';
		};
		document.onmouseup = function(){
			document.onmousemove = document.onmouseup =null;
		};
		return false;
	};

	onresize = function(){

		if(innerWidth<div1.offsetLeft+div1.offsetWidth){
			div1.style.left = innerWidth-div1.offsetWidth +'px'
		};

		if(innerHeight<div1.offsetTop+div1.offsetHeight){
			div1.style.top = div1.style.top = innerHeight-div1.offsetHeight +'px';
		}
	}



</script>
</body>
</html>